<?php
class Library_Model_TheChinhMapper extends Library_Model_DataMapperAbstract{
	private static $_instance = null;
	private $_paginator = null ;
	
	public function searchTheChinhById($id)
	{
		$db = $this->getDb();
		$selectThechinh = $db->select()
								->from('tbl_thechinh')
								->where('MaThe = ?',$id);
		$thechinh = $db->fetchRow($selectThechinh);

		$khachhangMapper = Library_Model_KhachHangMapper::getInstance();
		$khachhang = $khachhangMapper->searchById($thechinh['MaKhachHang']);
		$thechinh['tbl_khachhang'] = $khachhang;
		
		$chinhanhMapper = Library_Model_ChiNhanhMapper::getInstance();
		$chinhanh = $chinhanhMapper->searchChiNhanhById($thechinh['MaChiNhanh']);
		$thechinh['tbl_chinhanh'] = $chinhanh;
		
		return $this->_populate($thechinh);
	
	}
	public function thechinhList()
	{
		$db = $this->getDb();
		$selectThechinh = $db->select()
											->from('tbl_thechinh');
		$thechinhs = $db->fetchAll($selectThechinh);				
		$thechinhObjArray = array();
		foreach($thechinhs as $thechinh){
			
			$khachhangMapper = Library_Model_KhachHangMapper::getInstance();
			$khachhang = $khachhangMapper->searchById($thechinh['MaKhachHang']);
			$thechinh['tbl_khachhang'] = $khachhang;
			
				$chinhanhMapper = Library_Model_ChiNhanhMapper::getInstance();
				$chinhanh = $chinhanhMapper->searchChiNhanhById($thechinh['MaChiNhanh']);
				$thechinh['tbl_chinhanh'] = $chinhanh;
			
			$thechinhObjArray[] = $this->_populate($thechinh);
		}
	
		return $thechinhObjArray;
	}
	
	public function _populate($data){
		$obj = new Library_Model_TheChinh();
		
		$obj->setId($data['MaThe']);
		$obj->setMakhachhang($data['MaKhachHang']);
		$obj->setKhachhang($data['tbl_khachhang']);
		$obj->setMachinhanh($data['MaChiNhanh']);
		$obj->setChinhanh($data['tbl_chinhanh']);
		$obj->setNgaydangky($data['NgayDangKy']);
	
		return $obj;
	}
	
	protected function _insert(Library_Model_DomainObjectAbstract $obj){
		$db = $this->getDb();
		$data =array(
				
				'MaKhachHang'		=>$obj->getMakhachhang(),
				'MaChiNhanh'			=>$obj->getMachinhanh(),
				'NgayDangKy'		=>$obj->getNgaydangky()
		);
		$db->insert('tbl_thechinh',$data);
	}
	protected function _update(Library_Model_DomainObjectAbstract $obj){
	
		$db = $this->getDb();
		$data =array(	
				
				'MaKhachHang'		=> $obj->getMakhachhang(),
				'MaChiNhanh'			=>$obj->getMachinhanh(),
				'NgayDangKy'		=>$obj->getNgaydangky()
		);
		$where = $db->quoteInto('MaThe = ?', $obj->getId());
		$db->update('tbl_thechinh',$data,$where);
	}
	
	public function delete($id)
	{
		$db = $this->getDb();
		$where = $db->quoteInto('MaThe = ?',$id);
		$db->delete('tbl_thechinh',$where);
	}
	public static function getInstance(){
		if(!isset(self::$_instance)){
			$c = __CLASS__;
			self::$_instance = new $c;
		}
		return self::$_instance;
	}
}